//
//  YsGetPictureClipManager.m
//  YsGetPictureClip
//
//  Created by Cer on 2020/4/8.
//

#import "YsGetPictureClipManager.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <YYKit/YYKit.h>

@interface YsGetPictureClipManager() <UINavigationControllerDelegate, UIImagePickerControllerDelegate, TZImagePickerControllerDelegate>
@property (nonatomic, weak) UIViewController *vc;
@property (nonnull, nonatomic, copy)void(^completed)(UIImage * _Nullable image,id _Nullable asset);
@property (nonatomic, assign) YsGetPictureClipType pictrueClipType;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (strong, nonatomic) CLLocation *location;
@end

@implementation YsGetPictureClipManager

static YsGetPictureClipManager *manager = nil;

+ (nullable instancetype)shareManger
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [self new];
    });
    return manager;
}

- (void)pushImagePickerWithVC:(nonnull UIViewController *)vc type:(YsGetPictureClipType)type
addHandlersForcompleted:(nonnull void(^)(UIImage * _Nullable image, id _Nullable asset))completed
{
    NSParameterAssert(vc);
    NSParameterAssert(completed);
    if (![vc isKindOfClass:UIViewController.class]) return;
    self.pictrueClipType = type;
    [self initWithVC:vc addHandlersForcompleted:completed];
}

- (void)initWithVC:(UIViewController *)vc addHandlersForcompleted:(nonnull void(^)(UIImage * _Nullable image, id _Nullable asset))completed
{
    self.vc = vc;
    self.completed = completed;
    if (self.pictrueClipType == YsGetPictureClipTypeCamera) {
        [self pushImagePickerController];
    }else if (self.pictrueClipType == YsGetPictureClipTypeAlbum) {
        [self pushTZImagePickerController];
    }
}


// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locations) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = [locations firstObject];
    } failureBlock:^(NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = nil;
    }];
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];
        [mediaTypes addObject:(NSString *)kUTTypeImage];
        [self.vc presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSError *error =  [NSError errorWithDomain:@"ys.songhognkang.YsGetPictureClip" code:1000 userInfo:@{NSLocalizedDescriptionKey:@"模拟器中无法打开照相机,请在真机中使用"}];
        self.completed(nil, error);
    }
}

// 调用相册
- (void)pushTZImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = YES;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.sortAscendingByModificationDate = YES;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = NO;
    
    ///   裁剪
     imagePickerVc.allowCrop = YES;
       // 设置竖屏下的裁剪尺寸
       NSInteger left = 0;
     NSInteger widthHeight = self.vc.view.width - 2 * left;
     NSInteger top = (self.vc.view.height - widthHeight) / 2;
       imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
       imagePickerVc.scaleAspectFillCrop = YES;
        
    // You can get the photos by block, the same as by delegate.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        self.completed([photos objectOrNilAtIndex:0], [assets objectOrNilAtIndex:0]);
    }];
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.vc presentViewController:imagePickerVc animated:YES completion:nil];
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.vc.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.vc.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];

    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    [tzImagePickerVc showProgressHUD];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSDictionary *meta = [info objectForKey:UIImagePickerControllerMediaMetadata];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image meta:meta location:self.location completion:^(PHAsset *asset, NSError *error){
        [tzImagePickerVc hideProgressHUD];
            if (error) {
                NSLog(@"图片保存失败 %@",error);
                self.completed(nil, error);
            } else {
                TZAssetModel *assetModel = [[TZImageManager manager] createModelWithAsset:asset];
                TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assetModel.asset photo:image completion:self.completed];
                imagePicker.cropRect = CGRectMake(0,self.vc.view.centerY - kScreenWidth / 2.0, kScreenWidth, kScreenWidth);
                imagePicker.allowPickingImage = YES;
                imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
                [self.vc presentViewController:imagePicker animated:YES completion:nil];
            }
        }];
    }
}
@end
